<?php

namespace App\Http\Controllers\Admin\BlindBoxManager;

use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

//引用http请求类
use App\Response\Response;
use Illuminate\Support\Facades\DB;

class BlindBoxController extends BaseController
{

    /**
     * @api {post} /bland-box 盲盒-创建
     * @apiVersion 0.1.0
     * @apiName 盲盒管理-盲盒-创建
     * @apiGroup 盲盒管理
     * @apiParam {number} gift_id                           礼物id
     * @apiParam {number} quantity                          数量
     * @apiParam {number} action                            1当期 2下期
     * @apiParam {number} type                              1银 2铜 3金
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function create(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(), [
            'action'   => "required|numeric|in:1,2",
            'type'     => "required|numeric|in:100,101,102,103,104,105,106",
            'gift_id'  => 'required|numeric|integer|exists:mysql.ln_gift,id',
            'quantity' => 'required|numeric|min:1|max:2100000000',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $params = $request->only("type", "gift_id", "quantity");

        $res = app('repo_gift_box_prize');

        $rows = $res->addBlindBox($params, $request->input('action'));
        if (!$rows) {
            throw new BasicException(10001, "插入失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {delete} /bland-box 盲盒-删除
     * @apiVersion 0.1.0
     * @apiName 盲盒管理-盲盒-删除
     * @apiGroup 盲盒管理
     * @apiParam {string} ids                       字符串分割的id 必传
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function del(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(), [
            'action' => "required|numeric|in:1,2",
            'ids'    => 'required|string',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $idsStr = $request->input("ids");
        $idsArr = explode(",", $idsStr);

        $rows = app('repo_gift_box_prize')->delBlindBox($idsArr, $request->input("action"));
        if (!$rows) {
            throw new BasicException(10001, "删除失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {put} /bland-box 盲盒-修改
     * @apiVersion 0.1.0
     * @apiName 盲盒管理-盲盒-修改
     * @apiGroup 盲盒管理
     * @apiParam {number} id
     * @apiParam {number} gift_id                           礼物id
     * @apiParam {number} quantity                          数量
     * @apiParam {number} action                            1当期 2下期
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function update(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(), [
            'id'   => "required|integer",
            'action'   => "required|numeric|in:1,2",
            'gift_id'  => 'required|numeric|integer|exists:mysql.ln_gift,id',
            'quantity' => 'required|numeric|min:1|max:2100000000',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $res = app('repo_gift_box_prize');

        $params = $request->only('id', 'action', "gift_id", "quantity");
        $id = $params['id'];

        $rows = $res->saveBlindBox(["id" => $id], $params, $request->input("action"));

        return Response::sendData(true);
    }

    /**
     * @api {Put} /bland-box/editMore 批量修改
     * @apiGroup 盲盒管理-盲盒-批量修改
     * @apiParam {Int} action 1：本期；2：下期
     * @apiParam {string} info id,礼物id,礼物数量;id,礼物id,礼物数量
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200,
     * "data": []
     * }
     */
    public function editMore(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(), [
            'action' => "required|numeric|in:1,2",
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $action = $request->action;
        $info = $request->info;

        if ($action == 1) {
            $model = app("model_gift_box_prize");
        } else {
            $model = app("model_gift_box_prize_next");
        }

        $info = explode(';', $info);

        DB::beginTransaction();
        try {
            foreach ($info as $v) {
                if ($v) {
                    $tmp = explode(',', $v);
                    if (isset($tmp[0])) {
                        $id = $tmp[0];
                    } else {
                        throw new BasicException(0, '参数结构错误');
                    }
                    $record = $model->where('id', $id)->value('id');
                    if (empty($record)) {
                        throw new BasicException(0, '参数错误');
                    }

                    if (isset($tmp[1])) {
                        $giftId = $tmp[1];
                    } else {
                        throw new BasicException(0, '参数结构错误');
                    }
                    $gift = app('model_gift')->where('id', $giftId)/*->where('sold', 1)*/ ->value('id');
                    if (empty($gift)) {
                        throw new BasicException(0, '礼物不存在或已下架');
                    }

                    if (isset($tmp[2])) {
                        $quantity = $tmp[2];
                    } else {
                        throw new BasicException(0, '参数结构错误');
                    }
                    if (!is_numeric($quantity) || $quantity < 1 || $quantity > 2100000000) {
                        throw new BasicException(0, '礼物数量有误');
                    }
                    $model->where('id', $id)->update(['gift_id' => $giftId, 'quantity' => $quantity]);
                }
            }
            DB::commit();

            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    /**
     * @api {get} /bland-box 盲盒-列表
     * @apiVersion 0.1.0
     * @apiName 盲盒管理-盲盒-列表
     * @apiGroup 盲盒管理
     * @apiParam {number} action 1当期 2下期
     * @apiParam {number} type 1银盲盒 2铜盲盒 3金盲盒 4铜背包 5银背包 6金背包
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id(序号)": 116,
     * "gift_id(礼物id)": 253,
     * "type(类型 1银 2铜 3金)": 1,
     * "quantity(数量)": 2,
     * "name(礼物名称)": "夏秋之夜",
     * "price(价格)": 29999,
     * "picture(图片)": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f438910efe23.png",
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 10,
     * "next": null,
     * "total": 1
     * }
     * }
     * }
     */
    public function list(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'action'  => "required|numeric|in:1,2",
                'type'    => "required|numeric|in:100,101,102,103,104,105,106",
                'perPage' => 'filled|numeric',
                'page'    => 'filled|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $params = $request->input();
        $list = app('repo_gift_box_prize')->getBlindBoxQueryList($params, $params['action']);

        return Response::sendList($list);
    }

    /**
     * @api {Put} /bland-box/replacePool 替换奖池
     * @apiGroup 盲盒管理-盲盒列表
     * @apiParam {Int} type 1银盲盒 2铜盲盒 3金盲盒 4铜背包 5银背包 6金背包，必须
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200,
     * "data": []
     * }
     */
    public function replacePool(Request $request)
    {
        $v = app('validator')->make($request->all(), [
                'type' => "required|numeric|in:100,101,102,103,104,105,106",
            ]
        );
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $type = $request->type;

        DB::beginTransaction();

        try {
            //删除对应类型的本期奖池
            app('model_gift_box_prize')->where(['type' => $type])->delete();
            //查询对应类型的下期奖池
            $addData = app('model_gift_box_prize_next')
                ->select('gift_id', 'type', 'initial_weight', 'sold', 'game_type', 'revise_weight', 'quantity')
                ->where(['type' => $type])
                ->get()->toArray();
            if (empty($addData)) {
                throw new BasicException(0, '下期奖池为空');
            }

            app('model_gift_box_prize')->insert($addData);

            DB::commit();

            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }


    /**
     * @api {get} /bland-box/explain 盲盒配置列表
     * @apiGroup 盲盒管理-盲盒配置
     * @apiParam {Int} type（选填） 1银盲盒 2铜盲盒 3金盲盒
     * @apiParam {Int} perPage （选填） 页面尺寸
     * @apiParam {Int} page （选填） 页码
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id": 1,
     * "gift_id": 98,
     * "box_type（盲盒类型 1银盲盒 2铜盲盒 3金盲盒）": 1,
     * "sort（排序值）": 0,
     * "probability（概率 单位 %）": "0.00",
     * "created_at（创建时间）": "2021-11-16 17:54:17",
     * "updated_at（修改时间）": "2021-11-17 09:51:31",
     * "name（礼物名称）": "舞池派对",
     * "price（礼物价格）": 5200,
     * "picture（礼物图片）": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/MC5BhTnif8.png",
     * "special（礼物特效）": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/user-dir/eBRmeHybKR.svga"
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 20,
     * "next": null,
     * "total": 1
     * }
     * }
     * }
     */
    public function getBoxConfig(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'type'    => "numeric|in:100,101,102,103,104,105,106",
                'perPage' => 'filled|numeric',
                'page'    => 'filled|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $params = $request->input();
        $params['perPage'] = $params['perPage'] ?? 20;
        $params['page'] = $params['page'] ?? 1;
        $params['type'] = $params['type'] ?? 0;
        $list = app('repo_gift_box_prize')->getBlindBoxConfigList($params['type'], $params['perPage'], $params['page']);

        return Response::sendList($list);
    }

    /**
     * @api {post} /bland-box/explain 添加盲盒配置列表
     * @apiGroup 盲盒管理-盲盒配置
     * @apiParam {Int} type（必填） 1银盲盒 2铜盲盒 3金盲盒
     * @apiParam {Int} gift_id（必填） id
     * @apiParam {Int} sort（必填） 排序值
     * @apiParam {numeric} probability（必填） 概率 0.01-100
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"message":""}
     */
    public function addBoxConfig(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(), [
            'type'        => "required|numeric|in:100,101,102,103,104,105,106",
            'gift_id'     => 'required|numeric|integer|exists:mysql.ln_gift,id',
            'sort'        => 'required|integer|min:0',
            'probability' => 'required|numeric|min:0.01|max:100',

        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $params = $request->all();
        $data = [
            'gift_id'     => $params['gift_id'],
            'box_type'    => $params['type'],
            'sort'        => $params['sort'],
            'probability' => $params['probability'],
        ];
        $res = app('model_blind_box_config_gift')->create($data);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(10001, '添加失败');
        }
    }

    /**
     * @api {put} /bland-box/explain 修改盲盒配置列表
     * @apiGroup 盲盒管理-盲盒配置
     * @apiParam {Int} id（必填）
     * @apiParam {Int} type（必填） 1银盲盒 2铜盲盒 3金盲盒
     * @apiParam {Int} gift_id（必填） id
     * @apiParam {Int} sort（必填） 排序值
     * @apiParam {numeric} probability（必填） 概率 0.01-100
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"message":""}
     */
    public function editBoxConfig(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(), [
            'id'          => "required|integer",
            'type'        => "required|numeric|in:100,101,102,103,104,105,106",
            'gift_id'     => 'required|numeric|integer|exists:mysql.ln_gift,id',
            'sort'        => 'required|integer|min:0',
            'probability' => 'required|numeric|min:0.01|max:100',

        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $params = $request->all();
        $data = [
            'gift_id'     => $params['gift_id'],
            'box_type'    => $params['type'],
            'sort'        => $params['sort'],
            'probability' => $params['probability'],
        ];

        $res = app('model_blind_box_config_gift')->where('id', $params['id'])->update($data);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(10001, '修改失败');
        }
    }

    /**
     * @api {delete} /bland-box/explain 删除盲盒配置列表
     * @apiGroup 盲盒管理-盲盒配置
     * @apiParam {Int} id（必填）
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"message":""}
     */
    public function delBoxConfig(Request $request)
    {
        //参数校验
        $param = $request->all();
        $v = app('validator')->make($param, [
            'id' => "required|integer",

        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $res = app('model_blind_box_config_gift')->where('id', $param['id'])->delete();
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(10001, '删除失败');
        }
    }
}
